<route lang="json5">
	{
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '我的数据',
	enablePullDownRefresh: false,
	"app-plus": {
	"bounce": "none"
	}
	},
	}
</route>
<template>
	<view style="display: flex; flex-direction: column; height: 100vh;">
		<view style="position: sticky; top: 0; z-index: 9999">
			<wd-navbar title="我的数据" :bordered="false">
				<template #left>
					<wd-icon name="thin-arrow-left" size="16px" color="white" @click="goBack"></wd-icon>
				</template>
			</wd-navbar>
		</view>
		<view style="flex:1;background-color: #f4f4f4;overflow-y: auto;">
			<view v-if="storageList.length" class="tip">
				提示：数据默认存储在手机缓存中,可选择上传到数据库
			</view>
			<view v-if="!storageList.length" class="no-data"></view>
			<template v-for="(item,index) in storageList" :key="index">
				<view class="card" :id="`item-${index}`">
					<view class="content">
						<view class="range">
							<view class="title">
								<thInput v-if="item.editable" type="text" v-model:value="item.fileName"
									style="flex:1;margin-right:30rpx" clearable border></thInput>
								<view v-else class="index">{{item.fileName}}</view>
								<view v-if="item.editable">
									<th-button type="info" size="small" @click="editFileName(item,'cancel')">取消</th-button>
									<th-button  type="primary" size="small" @click="okHandle(item)" style="margin-left:15rpx">确定</th-button>
								</view>
								<text v-else class="iconfont icon-bianji" style="font-size:42rpx;color:#666" @click="editFileName(item)"></text>
							</view>
							<view class="time">{{item.localSaveTime}}</view>
							<view v-if="item.id === inPreview">
								<echarts :option="option" style="height: 300px"></echarts>
							</view>
							<view class="tool">
								<view>
									<th-button size="small" type="primary" @click="previewWave(item)"
										style="margin-right:20rpx">
										<text v-if="item.status===1">暂停</text>
										<text v-else-if="item.status===2">继续播放</text>
										<text v-else-if="item.status===3">重新播放</text>
										<text v-else>播放</text>
										</th-button>
									<th-button v-if="[1,2,3].includes(item.status)" size="small" type="warning" @click="quitPreview(item)"
											style="margin-right:20rpx">
											取消播放
											</th-button>
									<th-button size="small" type="danger" @click="clearHandle(item,index)">删除</th-button>
								</view>
								<th-button size="small" type="primary" v-if="item.type && !item.editable" @click="saveHandle(item)">未上传</th-button>
								<text style="color:#bfbfbf;font-size:26rpx" v-if="!item.type">已上传</text>
							</view>
						</view>
					</view>
				</view>
			</template>
		</view>

	</view>

</template>

<script lang="ts" setup>
	import thInput from '@/pages/pm/assay-report/component/th-input.vue';
	import thButton from '@/pages/pm/assay-report/component/th-button.vue';
	import { voiceList, historyList, historyInfo, saveHistoryInfo, updateHistoryInfo, deleteHistoryInfo } from '@/service/brain';
	import showModal from '@/utils/modal';

	const goBack = () => {
		uni.navigateBack();
	};
	
	let data = [];
	let now = new Date(1997, 9, 3);
	let oneDay = 24 * 3600 * 1000;
	let value = Math.random() * 1000;

	function randomData() {
		now = new Date(+now + oneDay);
		value = value + Math.random() * 21 - 10;
		return {
			name: now.toString(),
			value: [
				[now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
				0
			]
		};
	}

	const option = ref({
		id: 'wave001',
		grid: {
			show: false,
			right: 10,
			left: 5,
			containLabel: true,
			bottom: 10
		},
		xAxis: {
			type: 'time',
			show: false,
		},
		yAxis: {
			name: '单位：万',
			type: 'value',
			min: 0,
		},
		series: [
			{
				data,
				type: 'line',
				symbol: 'none',
				smooth: true,
				lineStyle: {
					width: 1
				}
			}
		]
	});


	const storageList = ref([])

	/**
	 * 声音播放
	**/
	// const innerAudioContext = uni.createInnerAudioContext();
	// console.log(innerAudioContext)
	// innerAudioContext.loop = true;
	const voiceListData = ref([]);

	const getVoiceList = () => {
		voiceList().then(res => {
			if (res.code === 0) {
				voiceListData.value = res.data.ruleList.map((item)=>{
					const  innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.src = item.voiceUrl;
					return {
						...item,
						innerAudioContext
					}
				})
			}
		})
	}


	const playVoice = (value : number) => {
		const voice = voiceListData.value.find(item => value > item.min && value <= item.max);
		voice.innerAudioContext.play();
	}

	const saveHandle = (item ?: any) => {
		uni.showLoading({
			title: '正在保存',
			mask: true
		})

		const data = JSON.parse(uni.getStorageSync(item.copyName || item.fileName));
		const localSaveTime = (item.copyName || item.fileName).split('_')[2];
		const brainData = data.join(',');
		saveHistoryInfo({
			fileName:item.fileName,
			brainData,
			localSaveTime,
			configId:'666666'
		}).then(res => {
			if (res.code === 0) {
				uni.hideLoading();
				uni.showToast({
					title: '保存成功',
					mask: true
				})
				uni.removeStorage({
					key: item.copyName || item.fileName,
					success: function (res) {
						getBrainDataList();
					},
					fail(err){
						console.log(err)
					}
				});
			}
		}).catch(err=>{
			uni.showToast({
			    title: err.msg || err.message || '保存失败,请重试',
			    icon: "none",
			    duration: 3000,
			});
		})
	}
	
	const editFileName = (item,action?:string)=>{
		if(action){
			item.fileName = item.copyName;
		}else{
			item.copyName = item.fileName;
		}

		item.editable = !item.editable;
	}
	
	const okHandle = (item)=>{
		// 本地存书，触发保存
		if(item.type){
			saveHandle(item);
		}else{
			// 只更新名称
			updateHandle(item);
		}
	}
	
	const updateHandle = (item)=>{
		uni.showLoading({
			title: '正在更新',
			mask: true
		})
		if(item.fileName.trim() === ''){
			uni.showToast({
				title:'不能为空',
				icon:'none'
			})
			return;
		}
		updateHistoryInfo({
			id:item.id,
			fileName:item.fileName
		}).then(res => {
			if (res.code === 0) {
				uni.hideLoading();
				uni.showToast({
					title: '保存成功',
					mask: true
				})
				item.editable = false;
			}
		}).catch(err=>{
			uni.showToast({
			    title: err.msg || err.message || '保存失败,请重试',
			    icon: "none",
			    duration: 3000,
			});
		})
	}

	const getHistoryList = () => {
		historyList().then(res => {
			if (res.code === 0) {
				storageList.value = [...storageList.value,...res.data.records];
			}
		})
	}
	
   const getValue = (id:string)=>{
	   return new Promise((resolve)=>{
		   historyInfo(id).then((res)=>{
			  if(res.code === 0){
				  resolve(res.data.brainData)
			  }else{
				  resolve(false)
			  }
		   }).catch(()=>{
			   resolve(false)
		   })
	   })
   }
    
	let timer=null;
	const inPreview= ref(null);
	const pause = ref(false);
	const currentItem = ref(null);
	const previewWave = async(item) => {
		// innerAudioContext.stop();
		if(item.id !== inPreview.value && currentItem.value){
			currentItem.value.status = 0;
		}
		if(item.status === 1){ // 正在播放 -> 暂停
			item.status = 2;
			pause.value = true;
			console.log('pause','----------')
			setTimeout(()=>{
				// innerAudioContext.pause();
			},200)
		}else if(item.status === 2){ // 暂停 -> 播放
			item.status = 1;
			pause.value = false;
			// innerAudioContext.play();
		}else{
			pause.value = false;
			// innerAudioContext.play();
			item.status = 1;
			currentItem.value = item;
			inPreview.value = item.id;
			if (item.type) {
			    const data = uni.getStorageSync(item.fileName);
			    sendWave(JSON.parse(data))
			} else {
				const value = await getValue(item.id);
				if(value){
					const arr = value.split(',');
					sendWave(arr)
				}
			}
		}
	}
	
	const quitPreview = (item)=>{
		item.status= 0;
		currentItem.value = null;
		inPreview.value = null
		if(timer){
			clearInterval(timer);
			timer = null;
			// innerAudioContext.stop();
		}
	}
	
	const sendWave = (arr)=>{
		if(timer){
			clearInterval(timer);
			timer = null;
		}
		let ind = 0;
		data = []
		for (var i = 0; i < 60; i++) {
			data.push(randomData());
		}
		option.value.series[0].data = data;
		timer = setInterval(()=>{
			if(ind === arr.length - 1){
				clearInterval(timer);
				// innerAudioContext.stop();
				currentItem.value.status = 3;
				return;
			}
			if(pause.value) return;
			now = new Date(+now + oneDay);
			option.value.series[0].data.shift();
			option.value.series[0].data.push({
				name: now.toString(),
				value: [[now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'), arr[ind] / 10000]
			});
			playVoice(arr[ind]);
			ind+=1;
		},1000)
	}

	const clearHandle = (item, index) => {
		showModal({
			title: '提示',
			content: '确定删除此条记录吗?',
			showCancel: true,
			confirm: async () => {
				// 本地删除
				if (item.type) {
					uni.removeStorage({
						key: item.fileName,
						success: function (res) {
							storageList.value.splice(index, 1)
						},
						fail(err){
							console.log(err)
						}
					});
				} else {
				    // 服务器删除
					deleteHistoryInfo([item.id]).then(res=>{
						if(res.code === 0){
							uni.showToast({
								title:'删除成功'
							})
							storageList.value.splice(index,1);
						}
					}).catch(err=>{
						console.log(err)
					})
				}
			},
		});
	}
	
	const getBrainDataList = ()=>{
		try {
			const res = uni.getStorageInfoSync();
			const keys = res.keys.filter(key => key.indexOf('brain_wave_') > -1);
			storageList.value = keys.reverse().map((key,index) => {
				return {
					id:index,
					fileName: key,
					type:'storage',
					value: []
				}
			})
			
			getHistoryList();
		} catch (e) {
			// error
		}
	}

	onMounted(() => {
		getVoiceList();
		getBrainDataList();
	})
	
	const quiet = ()=>{
		return new Promise((resolve)=>{
			if(timer){
				clearInterval(timer);
				timer = null;
			}
			// innerAudioContext.stop();
			// innerAudioContext.destroy();
			resolve(true)
		})
	}
	
	onBackPress(() => {
		quiet().then(back=>{
			return false;
		})
	})
</script>

<style lang="scss" scoped>
	@import url('@/static/iconfont/iconfont.css');

	.card {
		margin: 20rpx;
		display: flex;
		align-items: center;
		background:#fff;
		// box-shadow: 0 0 10rpx 0 #bfbfbf;
		border-radius: 10rpx;
		.content {
			flex: 1;
		}
	}
	.tip{
		text-align:left;
		padding:0 20rpx;
		font-size:26rpx;
		color:#333;
		margin-top:20rpx;
	}

	.range {
		padding: 15rpx 30rpx;
		border-bottom: 1rpx solid #f1f1f1;
		border-radius: 15rpx;
	}

	.row {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.title {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.index {
			line-height:64rpx;
			font-size: 36rpx;
			// font-weight: bold;
		}
	}
	.time{
		color:#666;
		font-size:28rpx;
		margin-top:15rpx;
		padding-bottom: 15rpx;
		border-bottom: 1rpx solid #bfbfbf;
	}

	.tool {
		margin-top: 20rpx;
		display:flex;
		align-items: center;
		justify-content: space-between;
	}
	.no-data{
		background: url(@/static/nodata.png) no-repeat center center;
		background-size: 400rpx 400rpx;
		height:400rpx;
		position:relative;
		&::after{
			content:'暂无数据';
			font-size: 28rpx;
			position:absolute;
			color:#bfbfbf;
			bottom:0;
			left:50%;
			transform:translateX(-50%);
		}
	}

	:deep(.wd-navbar__right--hover, .wd-navbar__left--hover) {
		background: none;
	}
</style>